package cn.pegasus.teamwork.weixinpay.service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import cn.pegasus.teamwork.weixinpay.configure.WxPayConfig;
import cn.pegasus.teamwork.weixinpay.util.HttpClientUtil;
import cn.pegasus.teamwork.weixinpay.util.WXPayUtil;
import cn.pegasus.teamwork.weixinpay.util.XMLUtil;
import net.sf.json.JSONObject;

/**
 * 自定义类，在官方文档中没有
 * 
 * @author 周立波
 *
 */
public class ServiceUtil {
	private static final Log logger = LogFactory.getLog(ServiceUtil.class);

	/**
	 * 第二步：通过code换取网页授权access_token
	 * 根据授权码code获取access_token，参考：http://mp.weixin.qq.com/wiki/17/
	 * c0f37d5704f0b64713d5d2c37b468d75.html#.E7.AC.AC.E4.BA.8C.E6.AD.A5.EF.BC.
	 * 9A.E9.80.9A.E8.BF.87code.E6.8D.A2.E5.8F.96.E7.BD.91.E9.A1.B5.E6.8E.88.E6.
	 * 9D.83access_token
	 */
	public static String getOpenId(String code) {
		String openParam = "appid=" + WxPayConfig.APP_ID + "&secret=" + WxPayConfig.APP_SECRET + "&code=" + code
				+ "&grant_type=authorization_code";
		String openJsonStr = HttpClientUtil.sendGET("https://api.weixin.qq.com/sns/oauth2/access_token", openParam);
		System.out.println("openJsonStr:" + openJsonStr);

		// 获取openid
		JSONObject openJson = JSONObject.fromObject(openJsonStr);
		String openid = openJson.getString("openid");
		return openid;
	}

	/**
	 * 统一下单接口 参考文档：https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1
	 * 
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static Map<String, String> unifiedorder(String requestXml) throws Exception {
		// 统一下单接口提交 xml格式
		URL orderUrl = new URL("https://api.mch.weixin.qq.com/pay/unifiedorder");
		HttpURLConnection conn = (HttpURLConnection) orderUrl.openConnection();
		conn.setConnectTimeout(30000); // 设置连接主机超时（单位：毫秒)
		conn.setReadTimeout(30000); // 设置从主机读取数据超时（单位：毫秒)
		conn.setDoOutput(true); // post请求参数要放在http正文内，顾设置成true，默认是false
		conn.setDoInput(true); // 设置是否从httpUrlConnection读入，默认情况下是true
		conn.setUseCaches(false); // Post 请求不能使用缓存
		// 设定传送的内容类型是可序列化的java对象(如果不设此项,在传送序列化对象时,当WEB服务默认的不是这种类型时可能抛java.io.EOFException)
		conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		conn.setRequestMethod("POST");// 设定请求的方法为"POST"，默认是GET
		conn.setRequestProperty("Content-Length", requestXml.length() + "");
		OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), WxPayConfig.CHARTSET);
		out.write(requestXml.toString());
		out.flush();
		out.close();
		if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
			return null;
		}
		// 获取响应内容体
		BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), WxPayConfig.CHARTSET));
		String line = "";
		StringBuffer strBuf = new StringBuffer();
		while ((line = in.readLine()) != null) {
			strBuf.append(line).append("\n");
		}
		in.close();
		System.out.println("result=========返回的xml=============" + strBuf.toString());
		Map<String, String> orderMap = XMLUtil.doXMLParse(strBuf.toString());
		System.out.println("orderMap===========================" + orderMap);

		// 获取
		// String prepay_id = orderMap.get("prepay_id");
		// String sign = orderMap.get("sign");
		return orderMap;
	}

	public static void main(String[] args) throws Exception {
		HashMap<String, String> data = new HashMap<String, String>();
		data.put("body", "凤凰共享洗车-会员充值");
		data.put("out_trade_no", "2018130910503433-402");
		// data.put("device_info", "1000");
		// data.put("fee_type", "CNY");
		data.put("total_fee", "1");
		data.put("spbill_create_ip", "127.0.0.1");
		data.put("notify_url", "http://120.79.92.124:8080/api/pro/gpl");
		data.put("trade_type", "APP");
		data.put("openid", "o8jJF07hOCr7sCvSvzGqlRzYUA6g");
		data.put("product_id", "8");
		data.put("sign_type", "MD5");

		String WX_PATERNERKEY = "9BA7ABCF11F036A23193BD74CE2A0502";
		String mch_id = "1494181972";
		String appid = "wx620cf6b8dddd4fb8";
		data.put("mch_id", mch_id);
		data.put("appid", appid);

		String nonce_str = WXPayUtil.generateNonceStr();
		System.out.println(nonce_str);
		data.put("nonce_str", "305cefcdbb484de8a62c442cbc31812c");
		String rs = WXPayUtil.generateSignedXml(data, WX_PATERNERKEY);
		Map<String, String> orderMap = unifiedorder(rs);
		System.out.println(orderMap);
	}
}
